package org.vaadin.addon.markdownlabel;


import com.github.rjeschke.txtmark.Processor;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.ClientWidget;
import com.vaadin.ui.Label;

import org.vaadin.addon.markdownlabel.client.ui.VMarkdownLabel;

/**
 * Server side component for the VMarkdownLabel widget.
 */

@ClientWidget(VMarkdownLabel.class)
public class MarkdownLabel extends Label {

	/** Array of content mode names that are rendered in UIDL as mode attribute. */
    private static final String[] CONTENT_MODE_NAME = { "text", "pre", "uidl",
            "xhtml", "xml", "raw", "markdown" };
	
	public static final int CONTENT_MARKDOWN = 6;
	
	boolean isMarkdownLabel = true;
	
	public MarkdownLabel() {
		this("");
	}
	
	public MarkdownLabel(String markdown) {
		this(markdown, CONTENT_MARKDOWN);
	}
	
	public MarkdownLabel(String markdown, int contentMode) {
		super(markdown, contentMode);
	}
	
	@Override
	public void paintContent(PaintTarget target) throws PaintException {
        if (getContentMode() != CONTENT_TEXT) {
            target.addAttribute("mode", CONTENT_MODE_NAME[getContentMode()]);
        }
        if (getContentMode() == CONTENT_TEXT) {
            target.addText(toString());
        } else if (getContentMode() == CONTENT_UIDL) {
            target.addUIDL(toString());
        } else if (getContentMode() == CONTENT_XHTML || getContentMode() == CONTENT_MARKDOWN) {
            target.startTag("data");
            target.addXMLSection("div", processMarkdown(toString()),
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
            target.endTag("data");
        } else if (getContentMode() == CONTENT_PREFORMATTED) {
            target.startTag("pre");
            target.addText(toString());
            target.endTag("pre");
        } else if (getContentMode() == CONTENT_XML) {
            target.addXMLSection("data", toString(), null);
        } else if (getContentMode() == CONTENT_RAW) {
            target.startTag("data");
            target.addAttribute("escape", false);
            target.addText(toString());
            target.endTag("data");
        }
	}
	
	private String processMarkdown(String markdown) {
		if(getContentMode() != CONTENT_MARKDOWN) {
			return markdown;
		}
				
		String result = Processor.process(markdown);
		return result;
	}
	
	@Override
	public void setContentMode(int contentMode) {
        if(contentMode == CONTENT_MARKDOWN) {
        	this.isMarkdownLabel = true;
        } else {
        	this.isMarkdownLabel = false;
        }
        super.setContentMode(contentMode);
    }
	
	@Override
	public int getContentMode() {
		if(this.isMarkdownLabel) {
			return CONTENT_MARKDOWN;
		} else {
			return super.getContentMode();
		}
	}

}
